<?php
/*
 Plugin Name: WP Cloud Backup
 Plugin URI: http://code.google.com/p/wp-cloud-backup
 Description: Backup your wordpress files in the cloud
 Version: 0.1
 Author: Canarduck
 Author URI: http://canarduck.com
 License: GPL2
 */

/*  Copyright 2010  Canarduck  (email : renaud@canarduck.com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

$wpcb_providers = array(
  'S3' => array('display'=> __('Amazon S3', 'wpcb'), 'library'=>'S3.php'), 
);
foreach($wpcb_providers as $k => $details) {
  require_once('providers/' . $details['library']);
}



function wpcb_init() {
  
  if($_POST['wpcb_test_access']) {
    wpcb_test_access();
  }
  
  if(false == get_option('wpcb_access_granted')) {
    wpcb_register_auth_settings();
  } else {
    wpcb_register_backup_settings();
  }
}

/**
 * Settings page
 * 
 * Output the html needed to set up the backup account, schedule, etc...
 *
 * @package wpcb
 * @since 0.1
 */
function wpcb_settings_page() {
  global $wpcb_providers;
?>
  <div class="wrap">
    <style type="text/css">
      #icon-wpcb{background:transparent url(<?php echo WP_CONTENT_URL.'/plugins/'.basename(dirname(__FILE__)) . '/'; ?>wpcb-icon.png) no-repeat}
    </style>
    <div class="icon32" id="icon-wpcb"><br/></div><h2><?php _e('WP Cloud Backup', 'wpcb') ?></h2>
		<?php if (false == get_option('wpcb_access_granted') && strlen(get_option('wpcb_access_key'))) { ?>
		<div class='error fade'>
      <p><?php _e('Login failure, please double check your access and secret key.', 'wpcb') ?></p>
    </div>
		<?php } ?>
		<form method="post" action="options.php">
    <?php settings_fields('wpcd-settings'); ?>
<?php if(false == get_option('wpcb_access_granted')) { ?>
      <h3><?php _e('Account', 'wpcb') ?></h3>
      <table class="form-table">
        <tr valign="top">
          <th scope="row"><label for="wpcb_provider"><?php _e('Cloud storage provider', 'wpcb') ?></label></th>
          <td>
            <select name="wpcb_provider">
            <?php foreach($wpcb_providers as $k => $details) { ?>
              <option value="<?php echo $k ?>"<?php if($k == get_option('wpcb_provider')) echo ' selected="selected"' ?>><?php echo $details['display'] ?></option>
            <?php } ?>
            </select>
            <span class="description"><?php _e('Only Amazon S3 is available for the moment...', 'wpcb'); ?></span>
          </td>
        </tr>
        <tr valign="top">
          <th scope="row"><label for="wpcb_access_key"><?php _e('Access key', 'wpcb') ?></label></th>
          <td>
            <input type="text" name="wpcb_access_key" value="<?php echo get_option('wpcb_access_key'); ?>" class="regular-text" />
          </td>
        </tr>
        
        <tr valign="top">
          <th scope="row"><label for="wpcb_secret_key"><?php _e('Secret key', 'wpcb') ?></label></th>
          <td>
            <input type="text" name="wpcb_secret_key" value="<?php echo get_option('wpcb_secret_key'); ?>" class="regular-text" />
            <span class="description"><?php _e('TODO: [security] display only when not set', 'wpcb'); ?></span>
          </td>
        </tr>
      </table>
      
      <p class="submit">
        <input type="submit" name="wpcb_test_access" class="button-primary" value="<?php _e('Save changes and test authentication') ?>" />
      </p>
<?php } else { ?>
      <h3><?php _e('What to backup ?') ?></h3>
      <p><?php _e('I would recommend a full backup of your blog maybe you\'ve got good reasons not to do so !', 'wpcb') ?></p> 
      <table class="form-table">
        <tr valign="top">
          <th scope="row"><?php _e('Files', 'wpcb') ?></th>
          <td>
            <fieldset>
              <legend class="screen-reader-text"><span><?php _e('Parts of your blog to back up', 'wpcb') ?></span></legend>
              <label for="wpcb_backup_wordpress">
                <input type="checkbox" name="wpcb_backup_wordpress" value="1" id="wpcb_backup_wordpress"<?php if(get_option('wpcb_backup_wordpress')) echo ' checked="checked"' ?> />
                <?php _e('Wordpress installation (theme, plugins, etc...)', 'wpcb') ?>
              </label><br />
              <label for="wpcb_backup_uploads">
                <input type="checkbox" name="wpcb_backup_uploads" value="1" id="wpcb_backup_uploads"<?php if(get_option('wpcb_backup_uploads')) echo ' checked="checked"' ?> />
                <?php _e('Uploads (media files, etc...)', 'wpcb') ?>
              </label><br />
              <label for="wpcb_backup_database">
                <input type="checkbox" name="wpcb_backup_database" value="1" id="wpcb_backup_database"<?php if(get_option('wpcb_backup_database')) echo ' checked="checked"' ?> />
                <?php _e('Database', 'wpcb') ?>
              </label>
            </fieldset>
          </td>
        </tr>
      </table>      
      
      <h3><?php _e('Where ?', 'wpcb') ?></h3>
      <p><?php _e('Each cloud storage providers use a different name for their "folders", amazon call them "buckets", etc... but you get the idea, where do you want to put your files ?', 'wpcb') ?></p>
      <table class="form-table">
        <tr valign="top">
          <th scope="row"><?php _e('Account used', 'wpcb') ?></th>
          <td><?php printf(__("%s using an access key beginning with <kbd>%s</kbd>."), $wpcb_providers[get_option('wpcb_provider')]['display'], substr(get_option('wpcb_access_key'), 0, 6)); ?> <a href=""><?php _e('edit', 'wpcb') ?></a></td>
        </tr>
        <tr valign="top">
          <th scope="row"><label for="wpcb_destination"><?php _e('Destination', 'wpcb') ?></label></th>
          <td>
            <fieldset>
              <legend class="screen-reader-text"><span><?php _e('Destination') ?></span></legend>
              <?php $i = 0; ?>
              <?php foreach(wpcb_list_destinations() as $destination) { ?> 
              <?php $i++ ?>
              <label>
                <input <?php if($destination == get_option('wpcb_destination')) echo 'checked="checked"' ?> type="radio" name="wpcb_destination" value="<?php echo $destination ?>" id="wpcb_destination_<?php echo $i ?>" />
                <?php echo $destination ?>
              </label><br />
              <?php } ?>
              <label>
                <input type="radio" name="wpcb_destination" value="__custom__" id="wpcb_destination_custom" /> <? _e('Create a new destination :', 'wpcb') ?>
                <input type="text" name="wpcb_new_destination" value="" class="" />
              </label>
              <span class="description"><?php _e('WP Cloud Backup will try to create this folder TODO : add location (US, EU, etc...)', 'wpcb'); ?></span>
            </fieldset>
          </td>
        </tr>
      </table>
      
      <h3><?php _e('When ?', 'wpcb') ?></h3>
      <p><?php _e('Scheduled backups are probably more efficient than manual backups (CRON never forgets!), choose wisely the recurency : the more you backup the more you\'ll pay for storage ! Except if you use the cleaning functions...', 'wpcb') ?></p>
      <table class="form-table">
        <tr valign="top">
          <th scope="row"><label for="wpcb_schedule"><?php _e('Backup schedule', 'wpcb') ?></label></th>
          <td>
            <select name="wpcb_schedule">
              <option value="disabled"<?php if('disabled' == get_option('wpcb_schedule')) echo ' selected="selected"' ?>><?php _e('Disabled') ?></option>
            <?php foreach(wp_get_schedules() as $k => $details) { ?>
              <option value="<?php echo $k ?>"<?php if($k == get_option('wpcb_schedule')) echo ' selected="selected"' ?>><?php echo $details['display'] ?></option>
            <?php } ?>
            
            </select>
            <span class="description"><?php _e('Select "disabled" to only do manual backups', 'wpcb'); ?></span>
          </td>
        </tr>
      </table>
      <h3><?php _e('Optional', 'wpcb') ?></h3>
      <table class="form-table">
        <tr valign="top">
          <th scope="row"><label for="wpcb_send_mail_to"><?php _e('Send an email to ', 'wpcb') ?></label></th>
          <td>
            <input type="text" name="wpcb_send_mail_to" value="<?php echo get_option('wpcb_send_mail_to'); ?>" class="regular-text" />
            <span class="description"><?php _e('when backup process is completed', 'wpcb'); ?></span>
          </td>
        </tr>
        <tr valign="top">
          <th scope="row"><label for=""><?php _e('Cleanup ', 'wpcb') ?></label></th>
          <td>
            <input type="text" name="" value="" class="regular-text" />
            <span class="description"><?php _e('TODO', 'wpcb'); ?></span>
          </td>
        </tr>
      </table>  
      <p class="submit">
        <input type="submit" name="wpcb_save" class="button-primary" value="<?php _e('Save changes') ?>" />
        <input type="submit" name="wpcb_save_and_backup" class="" value="<?php _e('Save changes and backup my files') ?>" />
      </p>
<?php } ?>      
    </form>
  </div>
<?php
}


function wpcb_backup() {
}

function wpcb_clean_backups() {
}

function wpcb_delete_backup() {
}

function wpcb_list_backups() {
}

/**
 * List available destinations
 * 
 * returns the list of available destinations (bukets, folders, whatever)
 *
 * @package wpcb
 * @since 0.1
 *
 * @return   array
 */
function wpcb_list_destinations() {
  $result = array();
  switch(get_option('wpcb_provider')) {
    case 'S3':
      $provider_s3 = new S3(get_option('wpcb_access_key'), get_option('wpcb_secret_key')); 
      $result = $provider_s3->listBuckets();
    break;
  }
  return $result;
}

/**
 * Test access
 * 
 * Test credentials provided by the user
 *
 * @package wpcb
 * @since 0.1
 *
 * @return   bool            true for success
 */
function wpcb_test_access() {
  $result = false;
  switch(get_option('wpcb_provider')) {
    case 'S3':
      $provider_s3 = new S3(get_option('wpcb_access_key'), get_option('wpcb_secret_key')); 
      //print_r($provider_s3->listBuckets());
      if(is_array($provider_s3->listBuckets())) {
       $result = true;
      }
    break;
  }
  update_option('wpcb_access_granted', $result);
  return $result;
}

/**
 * Add new schedules 
 * 
 * Add new schedules (weekly, fortnightly, monthly) for cron_schedules
 *
 * @package wpcb
 * @since 0.1
 *
 * @param    array    $schedules    automaticaly passed by add_filter('cron_schedules')
 * @return   array                  full schedule
 */
function wpcb_add_schedules($schedules) {
  $schedules['weekly'] 		    = array('interval' => 604800, 'display' => __('Once Weekly', 'wpcb'));
	$schedules['fortnightly'] 	= array('interval' => 1209600, 'display' => __('Once Fortnightly', 'wpcb'));
  $schedules['monthly'] 		  = array('interval' => 2592000, 'display' => __('Once Monthly', 'wpcb'));
  return $schedules;
}

/**
 * Register settings
 * 
 * Uses the Settings API to register & sanitize user settings
 *
 * @package wpcb
 * @since 0.1
 */
function wpcb_register_settings() {
  register_setting('wpcd-settings', 'wpcb_provider', 'wpcb_validate_provider');
  register_setting('wpcd-settings', 'wpcb_access_key', 'wp_filter_nohtml_kses');
  register_setting('wpcd-settings', 'wpcb_secret_key', 'wp_filter_nohtml_kses');
  register_setting('wpcd-settings', 'wpcb_access_granted', 'intval');
  register_setting('wpcd-settings', 'wpcb_destination', 'wp_filter_nohtml_kses');
  register_setting('wpcd-settings', 'wpcb_schedule', 'wpcb_validate_schedule');
  register_setting('wpcd-settings', 'wpcb_send_mail_to', 'sanitize_email');
  register_setting('wpcd-settings', 'wpcb_backup_wordpress', 'intval');
  register_setting('wpcd-settings', 'wpcb_backup_uploads', 'intval');
  register_setting('wpcd-settings', 'wpcb_backup_database', 'intval');
}

function wpcb_register_auth_settings() {
  register_setting('wpcd-settings', 'wpcb_provider', 'wpcb_validate_provider');
  register_setting('wpcd-settings', 'wpcb_access_key', 'wp_filter_nohtml_kses');
  register_setting('wpcd-settings', 'wpcb_secret_key', 'wp_filter_nohtml_kses');
}

function wpcb_register_backup_settings() {
  register_setting('wpcd-settings', 'wpcb_destination', 'wp_filter_nohtml_kses');
  register_setting('wpcd-settings', 'wpcb_schedule', 'wpcb_validate_schedule');
  register_setting('wpcd-settings', 'wpcb_send_mail_to', 'sanitize_email');
  register_setting('wpcd-settings', 'wpcb_backup_wordpress', 'intval');
  register_setting('wpcd-settings', 'wpcb_backup_uploads', 'intval');
  register_setting('wpcd-settings', 'wpcb_backup_database', 'intval');
}

/**
 * Validate provider 
 * 
 * Sanitize the provider input, if the key provided is not found in the list set at the beginning of the file, 
 * the key of the first valid provider is returned
 *
 * @package wpcb
 * @since 0.1
 *
 * @param    string    $key    wanted provider id
 * @return   string            a valid provider id
 */
function wpcb_validate_provider($key) {
  global $wpcb_providers;
  if(!array_key_exists($key, $wpcb_providers)) {
    return $wpcb_providers[0];
  }
  return $key;
}

/**
 * Validate schedule 
 * 
 * Sanitize the schedule input, if the key provided is not found in wp_get_schedules() 
 * the schedule will be 'disabled'
 *
 * @package wpcb
 * @since 0.1
 *
 * @param    string    $key    wanted schedule id
 * @return   string            a valid schedule id or disabled
 */
function wpcb_validate_schedule($key) {
  $valid_schedules = wp_get_schedules();
  if(!array_key_exists($key, $valid_schedules)) {
    return 'disabled';
  }
  return $key;
}

/**
 * Link to settings 
 *
 * @package wpcb
 * @since 0.1
 */
function wpcb_settings_link($links, $file) {
  if ($file == plugin_basename(__FILE__))
    $links[] = '<a href="' . admin_url('options-general.php?page=wpcb-settings') . '">' . __('Settings') . '</a>';
  return $links; 
}

add_action('admin_init', 'wpcb_init');
add_action('admin_menu', create_function('', "add_options_page(__('Cloud Backups', 'wpcb'), 'WP Cloud Backups', 'administrator', 'wpcb-settings', 'wpcb_settings_page');"));
add_filter('plugin_action_links', 'wpcb_settings_link', 10, 2);
